package xing2387.filtervideoplayer

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import xing2387.filtervideoplayer.databinding.ActivityMainBinding
import xing2387.filtervideoplayer.item.FilterVideoPageFragment
import xing2387.filtervideoplayer.item.VideoPageFragment
import xing2387.filtervideoplayer.videopager.VideoListAdapter
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {
    companion object {
        const val TAG = "MainActivity"
    }

    val binding: ActivityMainBinding by lazy {
        DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.activity_main, null, false
        )
    }

    var previousPosition = -1
    val adapter = VideoListAdapter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
    }

    private fun initView() {
        binding.viewPager2.adapter = adapter
//        binding.viewPager2.setPageTransformer { page, position -> {} }
        binding.viewPager2.offscreenPageLimit = 1
        binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (previousPosition == position) {
                    return
                }
                if (previousPosition >= 0 && previousPosition < adapter.itemCount) {
                    val previousFragment = adapter.getFragmentAtPosition(previousPosition)
                    if (previousFragment is VideoPageFragment) {
                        Log.d(TAG, "onPageSelected: onDetachPlayer $previousPosition，${previousFragment.hashCode()}")
                        previousFragment.onDetachPlayer()
                    }
                }
                val currFragment = adapter.getFragmentAtPosition(position)
                if (currFragment is VideoPageFragment) {
                    Log.d(TAG, "onPageSelected: onAttachPlayer $position，${currFragment.hashCode()}")
                    currFragment.onAttachPlayer()
                }
                previousPosition = position
            }
        })
        binding.viewPager2.currentItem = 0
    }

    private fun initData() {
        loadVideoList()
    }

    fun loadVideoList() {
        Observable.create<JsonArray> {
            val input = resources.assets.open("videos.json")
            it.onNext(JsonParser.parseReader(InputStreamReader(input)).asJsonArray)
        }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(
                { t -> onVideoListLoaded(t.map { it.asString }.toList()) },
                { Log.e(TAG, "accept: ", it) }
            )
    }

    private fun onVideoListLoaded(videoUrlList: List<String>) {
        adapter.setVideoUrlList(videoUrlList)
    }

}